import { createRouter, createWebHashHistory } from 'vue-router'
import routes from './routes'
import { getUserInfo } from '@/http/apis'
import { useMainStore } from '@/store/main'

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach(async (to, from, next) => {
  if (to.path === '/login') {
    next()
  } else {
    if (useMainStore() && useMainStore().nav.length === 0) {
      const resp = await getUserInfo()
      useMainStore().setNav(resp.data.res)
      const dynmicRoutes = addDynmicRoutes(resp.data.res)
      router.addRoute(dynmicRoutes)
      // next({ path: to.path })
      next({ ...to }) // 为了解决页面刷新时空白，跳转要指定目标对象
    } else {
      next()
    }
  }
})

function addDynmicRoutes(data) {
  const homeRoutes = routes.filter(v => v.path === '/home')[0]
  homeRoutes.children = []
  data.forEach(item => {
    homeRoutes.children.push({
      path: item.path, //财务管理
      name: item.name,
      component: () => import(`../views/home/content/${item.component}/index.vue`)
    })
  })

  return homeRoutes
}

export default router